<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class Team extends CI_Controller
{
    protected $sesja= null;
    protected $log  = null;
    protected $elems= null;
    
    public function __construct() 
    {
        parent::__construct();
        $this->load->model('Team_model','team');
        $this->sesja= $this->session->userdata('sesja');
        $this->log  = new Logevent();
        $this->elems= new Elements();
    }
    
    public function show_teams()
    {
        $head['h1'] = 'Wszystkie drużyny w systemie';
        $teams      = $this->team->get_teams();
        if($teams['stan'])
        {
            $cont['teams'] = $teams['wynik'];
            $this->elems->load_view($this->sesja,'team/show_teams',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'alert','Brak drużyn do pokazania',anchor('team/add_team','Dodaj następną drużynę',array('class'=>'btn btn-primary')));
    }
    
    public function add_team()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $head['h1'] = 'Dodaj nową drużynę';
            $ligi       = $this->team->get_leagues();
            if($ligi['stan'])
            {
                $cont['ligi'] = $ligi['wynik'];
                $this->elems->load_view($this->sesja,'team/add_team',$cont,$head);
            }
            else
                $this->elems->load_alert($this->sesja,'alert','Brak dostęppnych lig',anchor('league/add_league','Dodaj ligę'));
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function insert_team()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $this->load->library('form_validation');
            
            $this->form_validation->set_error_delimiters('<p class="error">','</p>');
            $this->form_validation->set_rules('name','Pełna nazwa','required|xss_clean');
            $this->form_validation->set_rules('code','Skrócona nazwa','required|xss_clean');
            $this->form_validation->set_rules('liga','Liga','required|integer|xss_clean');
            $this->form_validation->set_rules('sezon','Sezon/rok','integer|xss_clean');
            
            if($this->form_validation->run() == FALSE && isset($_POST['add_team']))
                $this->add_team();
            elseif($this->form_validation->run() == FALSE && isset($_POST['edit_team']))
                $this->edit_team($this->input->post('tid'));
            else
            {
                if(isset($_FILES))
                {
                    $upload['upload_path']  = $this->config->item('image_team_path');
                    $upload['allowed_types']= 'gif|jpg|png';
                    $upload['max_size']     = '2048';
                    $upload['file_name']    = date('Y-m-d-G-i-s-u').remove_pl($this->input->post('code').$this->input->post('sezon'));
                    $this->load->library('upload',$upload);
                    if($this->upload->do_upload('image'))
                    {
                        $image_info = $this->upload->data();
                        $team['team_logo'] = $image_info['full_path'];
                    }
                }
                $team['team_name']  = $this->input->post('name');
                $team['team_code']  = $this->input->post('code');
                if($this->team->insert_team($team))
                {
                    $leg['tl_team'] = $this->db->insert_id();
                    $leg['tl_league'] = $this->input->post('liga');
                    $leg['tl_season'] = $this->input->post('sezon');
                    if($this->team->insert_team_league($leg))
                        $this->elems->load_alert(
                                $this->sesja,
                                'success',
                                'Dodano drużynę: <strong>'.$team['team_name'].'</strong> do bazy.',
                                anchor('team/add_team','Dodaj następną drużynę',array('class'=>'btn btn-primary'))
                        );
                    else
                        $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania drużyny do ligi.');
                }
                else
                    $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania zawodnika/trenera do bazy:<br/>'.$this->db->last_query(),get_back_link());
            }
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function show_team($id)
    {
        $info = $this->team->get_team_info($id);
        $squad= $this->team->get_squad($id);
        
        if($info['stan'])
        {
            if($squad['stan'])
            {
                $head['h1']     = 'Skład drużyny: '.$info['wynik'][$id]['name'];
                $cont['squad']  = $squad['wynik'];
                $cont['info']   = $info['wynik'];
                $cont['admin']  = (isset($this->sesja)) ? $this->sesja['editor'] : 0;
                $foot['js']     = array(
                    'js/libs/tablesorter.js',
                    'js/team/show_team.js'
                );
                $this->elems->load_view($this->sesja,'team/show_team',$cont,$head,$foot);
            }
            else
                $this->elems->load_alert($this->sesja,'alert','Brak zawodników w drużynie');
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie ma takiej drużyny.');
        
    }
    
    public function add_player()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $head['h1'] = 'Dodaj zawodnika';
            $teams      = $this->team->get_teams();
            if($teams['stan'])
            {
                $cont['teams'] = $teams['wynik'];
                $pos    = $this->team->get_positions();
                if($pos['stan'])
                {
                    $cont['pos']= $pos['wynik'];
                    $foot['js'] = array('js/default/datepicker.js');
                    $this->elems->load_view($this->sesja,'team/add_player',$cont,$head,$foot);
                }
                else
                    $this->elems->load_alert($this->sesja,'alert','Brak zdefiniowanych pozycji zawodników');
            }
            else
                $this->elems->load_alert($this->sesja,'alert','Brak zdefiniowanych drużyn');
            
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function edit_player($id)
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && is_numeric($id))
        {
            $this->load->model('Users_model');
            $player = $this->Users_model->get_user($id);
            if($player['stan'])
            {
                $teams = $this->team->get_teams();
                if($teams['stan'])
                {
                    $cont['teams']  = $teams['wynik'];
                    $pos            = $this->team->get_positions();
                    if($pos['stan'])
                    {
                        $head['h1']     = 'Edycja zawodnika: '.$player['wynik'][$id]['name'];
                        $cont['user']   = $player['wynik'][$id];
                        $cont['pos']    = $pos['wynik'];
                        $cont['uid']    = $id;
                        $foot['js']     = array('js/default/datepicker.js');
                        $this->elems->load_view($this->sesja,'team/edit_player',$cont,$head,$foot);
                    }
                    else
                        $this->elems->load_alert($this->sesja,'alert','Brak zdefiniowanych pozycji zawodników',get_back_link());
                }
                else
                    $this->elems->load_alert($this->sesja,'alert','Brak zdefiniowanych drużyn',get_back_link());
            }
            else
                $this->elems->load_alert($this->sesja,'error','Nie ma takiej osoby',get_back_link());
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function insert_player()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $this->load->helper('security');
            $this->load->library('form_validation');
            
            $this->form_validation->set_error_delimiters('<p class="error">','</p>');
            $this->form_validation->set_rules('fname','Imię','required|xss_clean');
            $this->form_validation->set_rules('lname','Nazwisko','required|xss_clean');
            $this->form_validation->set_rules('team','Drużyna','required|integer|xss_clean');
            $this->form_validation->set_rules('numer','Numer','integer|xss_clean');
            $this->form_validation->set_rules('email','Email','required|valid_email|xss_clean');
            $this->form_validation->set_rules('data_urod','Data urodzenia','xss_clean');
            $this->form_validation->set_rules('joined','Data dołączenia do drużyny','xss_clean');
            
            if(($this->form_validation->run() == FALSE || match_date_format($this->input->post('data_urod'))) && isset($_POST['add_player']))
                $this->add_player();
            elseif(($this->form_validation->run() == FALSE || match_date_format($this->input->post('data_urod'))) && isset($_POST['edit_player']))
                $this->edit_player($this->input->post('pid'));
            else
            {
                if(!empty($_FILES['image']['name']))
                {
                    $upload['upload_path']  = $this->config->item('image_user_path');
                    $upload['allowed_types']= 'gif|jpg|png';
                    $upload['max_size']     = '2048';
                    $upload['file_name']    = date('Y-m-d-G-i-s-u').remove_pl($this->input->post('imie').$this->input->post('nazw'));
                    $this->load->library('upload',$upload);
                    if($this->upload->do_upload('image'))
                    {
                        $image_info = $this->upload->data();
                        $tab['user_image'] = $image_info['file_name'];
                    }
                    else
                        $this->elems->load_alert($this->sesja,'error',$this->upload->display_errors(),get_back_link());
                }
                $tab['user_fname']  = $this->input->post('fname');
                $tab['user_lname']  = $this->input->post('lname');
                $tab['user_login']  = remove_pl($this->input->post('fname')).'.'.remove_pl($this->input->post('lname'));
                $tab['user_pass']   = sha1(
                                        substr(remove_pl($this->input->post('fname')),0,5)
                                        .'.'
                                        .substr(remove_pl($this->input->post('lname')),0,5)
                                        .$this->config->item('encryption_key')
                                    );
                $tab['user_email']  = $this->input->post('email');
                $tab['user_phone']  = $this->input->post('phone');
                $tab['user_hash']   = md5(strtotime(date('Y-m-s')).$tab['user_fname'].'-'.$tab['user_lname']);
                $tab['user_birth']  = strtotime($this->input->post('data_urod'));
                if($this->input->post('add_player'))
                {
                    if($this->team->insert_user($tab))
                    {
                        $id = $this->db->insert_id();
                        $pos= $this->input->post('pos');
                        $nr = $this->input->post('numer');
                        $joined = (match_date_format($this->input->post('joined'))) ? strtotime($this->input->post('joined')) : strtotime(date('Y-m-d'));
                        $this->team->insert_player_team($id,$this->input->post('team'),$joined);
                        foreach($pos as $p)
                        {
                            $tab2['pp_user']    = $id;
                            $tab2['pp_pos']     = $p;
                            $tab2['pp_number']  = $nr;
                            if(!$this->team->insert_player_position($tab2))
                                $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania pozycji do bazy:<br/>'.$this->db->last_query(),get_back_link());
                        }
                        $this->load->library('email');
                        $this->email->to($tab['user_email']);
                        $this->email->from('info@unitedteam.pl', $this->sesja['name']);
                        $this->email->subject('Utworzono konto w systemie United Team');
                        $message =   '<p>Witaj '.$tab['user_fname'].' '.$tab['user_lname'].',<br/>'
                                    .'Właśnie utworzono konto w systemie United Team. Ten adres email został podany podczas zakładania konta.<br/>'
                                    .'Aby aktywować konto należy otworzyć następujący link: '.anchor('site/activate/'.$tab['user_hash'],'Aktywacja konta').'<br/>'
                                    .'Po aktywacji konta możesz się zalogować za pomocą podanego loginu i hasła.<br/><br/>'
                                    .'Pozdrawiam<br/>'
                                    .'Administrator systemu United Team</p>';
                        $this->email->message($message);
                        if(!$this->email->send())
                            $this->elems->load_alert($this->sesja,'error',$this->email->print_debugger());
                        else
                            $this->elems->load_alert($this->sesja,'success','Dodano osobę: <strong>'.$tab['user_fname'].' '.$tab['user_lname'].'</strong> do bazy.',anchor('team/add_player','Dodaj kolejną osobę',array('class'=>'btn btn-primary btn-large')));
                    }
                    else
                        $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania zawodnika/trenera do bazy:<br/>'.$this->db->last_query(),get_back_link());
                }
                elseif($this->input->post('edit_player'))
                {
                    pretty_print($_POST);
                }
                else
                    $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania/edycji zawodnika',get_back_link());
            }            
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony',get_back_link());
    }
    
    public function get_json_teams($cid='',$lid='')
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            return $this->team->get_json_teams($cid,$lid);
        }
        else
            return FALSE;
    }
}